<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="card-title">资料列表</span>
        <el-button type="primary" size="small" style="float: right" @click="handleAdd">新增</el-button>
      </div>
      <el-table 
        v-loading="listLoading" 
        :data="tableData" 
        size="small" 
        class="table" 
        highlight-current-row
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="名称" min-width="200" />
        <el-table-column prop="categoryName" label="型号" min-width="150" />
        <el-table-column prop="categoryName" label="分类" min-width="150" />
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="listPram.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listPram.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        style="margin-top: 20px; text-align: right"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="materialForm"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入资料名称"
            maxlength="100"
            clearable
          />
        </el-form-item>
         <el-form-item label="型号" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入设备型号"
            maxlength="100"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="资料分类" prop="categoryId">
          <el-select
            v-model="formData.categoryId"
            placeholder="请选择资料分类"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="文件上传" prop="fileUrl">
          <el-upload
            class="upload-demo"
            action=""
            :http-request="handleUploadFile"
            :before-upload="beforeUpload"
            :file-list="fileList"
            :limit="1"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              支持上传pdf、doc、docx、xls、xlsx、ppt、pptx等文件，文件大小不超过50MB
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { filePdfApi } from '@/api/systemSetting';

export default {
  name: 'UploadTheMaterialsList',
  data() {
    return {
      listLoading: false,
      tableData: [],
      total: 0,
      listPram: {
        page: 1,
        limit: 10,
      },
      // 弹窗相关
      dialogVisible: false,
      dialogTitle: '新增资料',
      isEdit: false,
      submitLoading: false,
      // 表单数据
      formData: {
        id: null,
        name: '',
        categoryId: null,
        fileUrl: '',
        fileName: '',
      },
      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入资料名称', trigger: 'blur' },
        ],
        categoryId: [
          { required: true, message: '请选择资料分类', trigger: 'change' },
        ],
        fileUrl: [
          { required: true, message: '请上传文件', trigger: 'change' },
        ],
      },
      // 分类列表
      categoryList: [],
      // 文件上传相关
      fileList: [],
    };
  },
  mounted() {
    this.getList();
    this.getCategoryList();
  },
  methods: {
    // 获取分类列表
    getCategoryList() {
      // TODO: 调用接口获取分类数据
      // 示例：
      // getCategoryListApi().then((res) => {
      //   this.categoryList = res;
      // });
    },
    // 获取列表数据
    getList() {
      this.listLoading = true;
      // TODO: 调用接口获取数据
      // 示例：
      // materialListApi(this.listPram).then((res) => {
      //   this.tableData = res.list;
      //   this.total = res.total;
      //   this.listLoading = false;
      // }).catch(() => {
      //   this.listLoading = false;
      // });
      this.listLoading = false;
    },
    // 新增
    handleAdd() {
      this.isEdit = false;
      this.dialogTitle = '新增资料';
      this.resetForm();
      this.dialogVisible = true;
    },
    // 编辑
    handleEdit(row) {
      this.isEdit = true;
      this.dialogTitle = '编辑资料';
      this.formData = {
        id: row.id,
        name: row.name,
        categoryId: row.categoryId,
        fileUrl: row.fileUrl,
        fileName: row.fileName,
      };
      // 如果已有文件，显示在文件列表中
      if (row.fileName && row.fileUrl) {
        this.fileList = [{
          name: row.fileName,
          url: row.fileUrl,
        }];
      }
      this.dialogVisible = true;
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该资料吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        // TODO: 调用删除接口
        // 示例：
        // deleteMaterialApi({ id: row.id }).then((res) => {
        //   this.$message.success('删除成功');
        //   this.getList();
        // });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 分页
    handleSizeChange(val) {
      this.listPram.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listPram.page = val;
      this.getList();
    },
    // 文件上传前的校验
    beforeUpload(file) {
      const allowedTypes = [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-powerpoint',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
      ];
      const isAllowedType = allowedTypes.includes(file.type) || 
                           file.name.match(/\.(pdf|doc|docx|xls|xlsx|ppt|pptx)$/i);
      const isLt50M = file.size / 1024 / 1024 < 50;

      if (!isAllowedType) {
        this.$message.error('只能上传pdf、doc、docx、xls、xlsx、ppt、pptx格式的文件！');
        return false;
      }
      if (!isLt50M) {
        this.$message.error('上传文件大小不能超过 50MB！');
        return false;
      }
      return true;
    },
    // 自定义文件上传
    handleUploadFile(param) {
      const formData = new FormData();
      formData.append('multipart', param.file);
      
      const loading = this.$loading({
        lock: true,
        text: '上传中，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      
      // 调用 /admin/upload/pdf 接口，传递 model=product 和 pid=0
      filePdfApi(formData, { model: 'product', pid: 0 })
        .then((res) => {
          loading.close();
          if (res) {
            this.formData.fileUrl = res.sattDir || res.path || res.url;
            this.formData.fileName = param.file.name;
            this.$message.success('文件上传成功');
            // 手动触发表单验证
            this.$refs.materialForm.validateField('fileUrl');
          } else {
            this.$message.error('文件上传失败，请重试');
          }
        })
        .catch((err) => {
          loading.close();
          this.$message.error('文件上传失败：' + (err.message || '请重试'));
        });
    },
    // 文件超出个数限制
    handleExceed(files, fileList) {
      this.$message.warning('只能上传1个文件');
    },
    // 删除文件
    handleRemove(file, fileList) {
      this.formData.fileUrl = '';
      this.formData.fileName = '';
    },
    // 提交表单
    handleSubmit() {
      this.$refs.materialForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          // TODO: 调用接口保存数据
          // 示例：
          // const apiMethod = this.isEdit ? updateMaterialApi : addMaterialApi;
          // apiMethod(this.formData).then((res) => {
          //   this.$message.success(this.isEdit ? '编辑成功' : '新增成功');
          //   this.submitLoading = false;
          //   this.dialogVisible = false;
          //   this.getList();
          // }).catch(() => {
          //   this.submitLoading = false;
          // });
          this.submitLoading = false;
        } else {
          this.$message.error('请完善表单信息');
          return false;
        }
      });
    },
    // 关闭弹窗
    handleDialogClose() {
      this.resetForm();
    },
    // 重置表单
    resetForm() {
      this.formData = {
        id: null,
        name: '',
        categoryId: null,
        fileUrl: '',
        fileName: '',
      };
      this.fileList = [];
      if (this.$refs.materialForm) {
        this.$refs.materialForm.resetFields();
      }
    },
  },
};
</script>

<style scoped lang="scss">
.divBox {
  padding: 20px;
}

.box-card {
  min-height: calc(100vh - 120px);
}

.card-title {
  font-size: 16px;
  font-weight: 500;
}

.upload-demo {
  width: 100%;
}

.el-upload__tip {
  color: #999;
  font-size: 12px;
  line-height: 1.5;
  margin-top: 5px;
}
</style>